<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>vue锚点平滑滚动</title>
		<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
	</head>
	<body>
		<div id="demo-app" v-cloak>
			<div class="demo-left" ref="demoLeft" @scroll="onScroll">
				<div class="left-box" v-for="(v) in 4" :key="v" ref="leftBox">
					<span>{{v}}</span>
				</div>
			</div>
			<div class="demo-right">
				<div class="right-nav-box">
					<div class="right-nav" v-for="(v,k) in 4" :key="k" @click="onHandlerClick(k)" :class="{'right-nav-active': active === k}"
					 ref="rightNav">{{v}}</div>
				</div>
			</div>
		</div>
	</body>

	<script>
		const vm = new Vue({
			el: '#demo-app',
			data() {
				return {
					active: 0,
					activeArr: []
				}
			},
			mounted() {
				this.init()
			},
			methods: {
				init() {
					this.$nextTick(() => {
						setTimeout(() => {
							this.activeArr = []
							this.$refs['leftBox'].map(item => {
								item.style.background = `#${Math.floor(Math.random() * 0xffffff).toString(16)}`
								this.activeArr.push(item.offsetTop)
							})
						}, 300) // 延时加载，防止拿到的数值不准确
					})
				},
				onHandlerClick(index) {
                    console.log(index,'11111111');
					this.$refs['demoLeft'].scrollTo({
						top: this.$refs['leftBox'][index].offsetTop,
						behavior: 'smooth'
					})
				},
				onScroll(e) {
					this.activeArr.map((item, index) => {
                        console.log(item, index);
						if (e.target.scrollTop + 200 >= item) {
							this.active = index
						}
					})
				}
			}
		})
	</script>

	<style>
		[v-cloak] {
			display: none;
		}

		* {
			margin: 0;
			padding: 0;
			box-sizing: border-box;
		}

		html,
		body {
			width: 100%;
			height: 100%;
			overflow: hidden;
		}

		#demo-app {
			display: flex;
			width: 100%;
			height: 100%;
            flex-direction: column-reverse;
		}

		.demo-left {
			flex: 1;
			flex-shrink: 1;
			overflow: auto;
		}

		.left-box {
			width: 100%;
			height: 100%;
			display: flex;
		}

		.left-box span {
			margin: auto;
			font-size: 70px;
		}

		.demo-right {
			/* flex-basis: 100px; */
			display: flex;
			flex-direction: column;
		}

		.right-nav-box {
			display: flex;
		}

		.right-nav {
			border: 1px solid #09F;
			border-bottom: none;
			width: 100%;
			height: 50px;
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;
		}

		.right-nav:last-child {
			border-bottom: 1px solid #09F;
		}

		.right-nav-active {
			background: #09F;
			color: white;
		}

		.right-nav:hover {
			background: rgba(8, 58, 91, 0.53);
			color: white;
		}
	</style>
</html>


